package cn.tedu.ximart.server.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;

/**
 * JWT工具类
 * @author java@tedu.cn
 */
@Slf4j
public final class JwtUtils {

    private static final String SECRET_KEY = "lkjfdslkjafds8iufnmdsfadsa";
    private static final long EXPIRED_IN_MINUTE = 70*24*60;

    //无参构造方法，避免被多次创建
    private JwtUtils(){};

    /**
     * 生成JWT
     * @param claims 希望在JWT中封装的数据
     * @return JWT字符串
     */
    public static String  generate(Map<String,Object> claims){
        Date expiration = new Date(System.currentTimeMillis()+EXPIRED_IN_MINUTE*60*1000);
        String jwt = Jwts.builder()
                .setHeaderParam("typ","jwt")
                .setHeaderParam("alg","HS256")
                .setClaims(claims)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256,SECRET_KEY)
                .compact();
        log.debug("生成JWT数据：{}",jwt);
        return jwt;
    }

    /**
     * 解析JWT
     * @param jwt 需要解析的JWT数据
     * @return 解析得到的Claims，里面封装了生成JWT时存入的数据
     */
    public static Claims parse(String jwt){
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(jwt).getBody();
    }


}
